class DisasterMonitoring {
    constructor() {
        this.map = null;
        this.charts = {};
        this.currentTimeRange = 'week';
        this.currentMapView = 'satellite';
        this.alerts = []; // 存储预警信息
        this.records = []; // 存储处理记录

        this.initializeMap();
        this.initializeCharts();
        this.setupEventListeners();
        this.loadData();
    }

    initializeMap() {
        // 华兴农场中心坐标
        const FARM_CENTER = [44.2335295, 87.3130815];
        this.map = L.map('disasterMap').setView(FARM_CENTER, 15);

        // 添加卫星底图
        this.satelliteLayer = L.tileLayer('https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', {
            subdomains: ["1", "2", "3", "4"],
            attribution: '© 高德地图'
        }).addTo(this.map);

        // 添加地形图层
        this.terrainLayer = L.tileLayer('https://webst0{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}', {
            subdomains: ["1", "2", "3", "4"]
        });

        // 定义农场地块边界
        const plotBoundaries = {
            plot1: [ // A区水稻田
                [
                    [44.2345295, 87.3120815],
                    [44.2345295, 87.3140815],
                    [44.2325295, 87.3140815],
                    [44.2325295, 87.3120815]
                ]
            ],
            plot2: [ // B区玉米地
                [
                    [44.2325295, 87.3120815],
                    [44.2325295, 87.3140815],
                    [44.2305295, 87.3140815],
                    [44.2305295, 87.3120815]
                ]
            ],
            plot3: [ // C区小麦地
                [
                    [44.2345295, 87.3140815],
                    [44.2345295, 87.3160815],
                    [44.2325295, 87.3160815],
                    [44.2325295, 87.3140815]
                ]
            ]
        };

        // 绘制地块边界
        this.plotLayers = {};
        Object.entries(plotBoundaries).forEach(([plotId, coordinates]) => {
            const plotLayer = L.polygon(coordinates, {
                color: '#2ecc71',
                weight: 2,
                opacity: 0.8,
                fillOpacity: 0.1
            }).addTo(this.map);
            this.plotLayers[plotId] = plotLayer;
        });

        // 添加灾害标记
        this.updateDisasterMarkers();
    }

    initializeCharts() {
        // 初始化趋势图表
        const trendChart = echarts.init(document.getElementById('trendChart'));
        
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['病虫害', '气象灾害', '病害']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '病虫害',
                    type: 'line',
                    data: [3, 4, 2, 3, 2, 4, 2],
                    itemStyle: {
                        color: '#2ecc71'
                    }
                },
                {
                    name: '气象灾害',
                    type: 'line',
                    data: [2, 1, 3, 2, 3, 1, 2],
                    itemStyle: {
                        color: '#3498db'
                    }
                },
                {
                    name: '病害',
                    type: 'line',
                    data: [1, 2, 1, 2, 1, 1, 0],
                    itemStyle: {
                        color: '#e74c3c'
                    }
                }
            ]
        };

        trendChart.setOption(option);
        this.charts.trend = trendChart;

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.charts.trend.resize();
        });
    }

    setupEventListeners() {
        // 地图视图切换
        document.querySelectorAll('.btn-control').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const view = e.target.closest('.btn-control').dataset.view;
                this.switchMapView(view);
            });
        });

        // 时间范围切换
        document.querySelectorAll('.btn-time').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const range = e.target.dataset.range;
                this.updateTrendChart(range);
            });
        });

        // 筛选条件变化
        document.getElementById('disasterType').addEventListener('change', () => {
            this.updateFilters();
        });

        document.querySelectorAll('.severity-options input').forEach(checkbox => {
            checkbox.addEventListener('change', () => {
                this.updateFilters();
            });
        });

        // 标记处理按钮
        document.querySelectorAll('.mark-handled').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const alertItem = e.target.closest('.alert-item');
                this.handleAlert(alertItem);
            });
        });
    }

    switchMapView(view) {
        // 切换地图视图
        document.querySelectorAll('.btn-control').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-view="${view}"]`).classList.add('active');

        if (view === 'satellite') {
            this.map.removeLayer(this.terrainLayer);
            this.satelliteLayer.addTo(this.map);
        } else {
            this.map.removeLayer(this.satelliteLayer);
            this.terrainLayer.addTo(this.map);
        }
    }

    updateTrendChart(range) {
        // 更新时间范围按钮状态
        document.querySelectorAll('.btn-time').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-range="${range}"]`).classList.add('active');

        // 更新图表数据
        const data = this.getTrendData(range);
        this.charts.trend.setOption({
            xAxis: {
                data: data.dates
            },
            series: [
                {
                    name: '病虫害',
                    data: data.pest
                },
                {
                    name: '气象灾害',
                    data: data.weather
                },
                {
                    name: '病害',
                    data: data.disease
                }
            ]
        });
    }

    getTrendData(range) {
        // 模拟不同时间范围的数据
        const data = {
            week: {
                dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                pest: [3, 4, 2, 3, 2, 4, 2],
                weather: [2, 1, 3, 2, 3, 1, 2],
                disease: [1, 2, 1, 2, 1, 1, 0]
            },
            month: {
                dates: ['第1周', '第2周', '第3周', '第4周'],
                pest: [12, 15, 10, 8],
                weather: [5, 8, 12, 6],
                disease: [3, 5, 4, 2]
            },
            year: {
                dates: ['1月', '2月', '3月', '4月', '5月', '6月'],
                pest: [20, 15, 25, 30, 35, 25],
                weather: [15, 10, 20, 25, 15, 20],
                disease: [8, 5, 12, 15, 10, 8]
            }
        };
        return data[range];
    }

    handleAlert(alertItem) {
        // 添加处理动画
        alertItem.classList.add('handling');
        
        // 模拟处理过程
        setTimeout(() => {
            // 更新处理记录
            const recordList = document.querySelector('.record-list');
            const newRecord = document.createElement('div');
            newRecord.className = 'record-item';
            newRecord.innerHTML = `
                <div class="record-time">${new Date().toLocaleString()}</div>
                <div class="record-content">
                    <h4>已处理：${alertItem.querySelector('.alert-type').textContent}</h4>
                    <p>${alertItem.querySelector('.alert-content p').textContent}</p>
                </div>
                <div class="record-status completed">
                    <i class="fas fa-check-circle"></i> 已完成
                </div>
            `;
            recordList.insertBefore(newRecord, recordList.firstChild);

            // 移除预警
            alertItem.remove();

            // 更新预警数量
            const badge = document.querySelector('.badge.warning');
            const currentCount = parseInt(badge.textContent);
            badge.textContent = currentCount - 1;

            // 显示成功提示
            this.showToast('已成功处理预警');
        }, 1000);
    }

    showToast(message) {
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = message;
        document.body.appendChild(toast);

        // 显示动画
        setTimeout(() => toast.classList.add('show'), 100);

        // 自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    updateDisasterMarkers() {
        // 添加灾害标记示例
        const disasters = [
            {
                type: 'pest',
                location: [44.2345295, 87.3120815],
                title: '病虫害',
                description: 'A区水稻田发现稻飞虱感染'
            },
            {
                type: 'weather',
                location: [44.2325295, 87.3140815],
                title: '积水',
                description: 'B区出现积水情况'
            }
        ];

        disasters.forEach(disaster => {
            const icon = L.divIcon({
                className: `disaster-marker ${disaster.type}`,
                html: `<i class="fas ${this.getDisasterIcon(disaster.type)}"></i>`,
                iconSize: [30, 30]
            });

            L.marker(disaster.location, { icon })
                .addTo(this.map)
                .bindPopup(`
                    <div class="disaster-popup">
                        <h4>${disaster.title}</h4>
                        <p>${disaster.description}</p>
                    </div>
                `);
        });
    }

    getDisasterIcon(type) {
        const icons = {
            pest: 'fa-bug',
            weather: 'fa-cloud-showers-heavy',
            disease: 'fa-virus'
        };
        return icons[type] || 'fa-exclamation-triangle';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new DisasterMonitoring();
}); 